from prg.common.common_base import CommonBase
from prg.udp_data import UdpData
from prg.common.object_message import MessageBase
from prg.common.import_file import *


class UdpReceiveBytes(MessageBase):
    def __init__(self, addr):
        super().__init__(name="read_bytes")
        self.addr = addr
        self.udp_recv_array = None
        self.local_link = None
        self.task_id = None
        self.encryption = None

    def add_local_link(self, link_item):
        self.local_link = link_item

    def run_recv(self, udp_recv_array, task_id, encryption=None):
        self.encryption = encryption
        self.task_id = task_id
        self.udp_recv_array = udp_recv_array
        self.start()

    def command(self, cmd):
        if "close" == cmd.command:
            self.release()

    def entry(self):
        while self.is_run():
            udp_data = UdpData(bytes_array=self.udp_recv_array)
            udp_data.bind(encryption=self.encryption)
            if 0 == udp_data.name:
                json_str = udp_data.byte_data.decode("utf-8")
                en = CommonBase.json_to_entity(json_str=json_str, en=UdpCommandEntity())
                print("udp command: %s, from %s" % (en.command, str(self.addr)))
                self.command(en)
            else:
                if len(udp_data.byte_data) > 0:
                    self.local_link.add_data(name=udp_data.name, number=udp_data.number, byte_data=udp_data.byte_data)

